// 管理员建议反馈页面
const auth = require('../../../utils/auth')
const complaintsAPI = require('../../../api/complaints')

Page({
  data: {
    stats: {
      total: 0,
      pending: 0,
      today: 0
    },
    currentFilter: 'all',
    searchKeyword: '',
    filteredFeedbacks: [],
    feedbacks: [],
    showReplyModal: false,
    currentFeedback: {},
    replyContent: '',
    replyStatus: 'processing',
    showReplyError: false,
    replyErrorMsg: '',
    loading: false,
    error: null,
    // 全局加载状态
    globalLoading: false,
    globalLoadingText: '管理数据加载中...',
    // 详情弹窗状态
    showDetailModal: false,
    detailFeedback: {}
  },

  // 显示全局加载
  showGlobalLoading(text = '管理数据加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

  onLoad() {
    console.log('建议反馈页面加载')
    this.checkAuth()
    this.loadFeedbacks()
  },

  onShow() {
    console.log('建议反馈页面显示')
    this.loadFeedbacks()
  },

  // 检查权限
  checkAuth() {
    const role = auth.getCurrentRole()
    if (!role || role !== 'admin') {
      wx.showToast({
        title: '权限不足',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }
  },

  // 加载反馈数据
  async loadFeedbacks() {
    try {
      this.setData({
        loading: true,
        error: null
      })

      // 并行获取投诉建议列表和统计数据
      console.log('开始调用API获取数据...')
      const [complaintsResponse, statsResponse] = await Promise.all([
        complaintsAPI.getAllComplaints({
          status: this.data.currentFilter,
          page: 1,
          limit: 100 // 获取更多数据，实际项目中可以分页加载
        }),
        complaintsAPI.getAdminComplaintStats()
      ])
      
      console.log('API调用结果:', { complaintsResponse, statsResponse })

      // 处理投诉建议数据
      const complaints = complaintsResponse.data?.complaints || []
      const formattedFeedbacks = complaints.map(complaint => {
        // 根据类型设置图标
        const typeIcons = {
          'service': '🏛️',
          'efficiency': '⏰', 
          'facility': '🏢',
          'other': '💬'
        }

        // 根据状态设置文本和样式
        const statusConfig = {
          'pending': { text: '待处理', class: 'pending' },
          'processing': { text: '处理中', class: 'processing' },
          'completed': { text: '已处理', class: 'completed' },
          'cancelled': { text: '已撤销', class: 'cancelled' }
        }

        const statusInfo = statusConfig[complaint.status] || { text: '未知', class: 'unknown' }

        // 处理回复历史记录
        const replyHistory = (complaint.replies || []).map(reply => ({
          id: reply.id,
          content: reply.content,
          replyBy: reply.replyBy,
          replyTime: this.formatDateTime(new Date(reply.replyTime)),
          status: reply.status,
          statusText: reply.status === 'processing' ? '处理中' : '已完成'
        }))

        return {
          id: complaint.id,
          type: this.getTypeDisplayName(complaint.type),
          typeIcon: typeIcons[complaint.type] || '💬',
          title: complaint.title,
          content: complaint.content,
          userName: complaint.userName || '未知用户',
          createTime: this.formatDateTime(new Date(complaint.submitTime)),
          status: complaint.status,
          statusText: statusInfo.text,
          statusClass: statusInfo.class,
          urgent: complaint.urgent,
          lastUpdateTime: complaint.lastUpdateTime ? this.formatDateTime(new Date(complaint.lastUpdateTime)) : null,
          replyHistory: replyHistory,
          statusHistory: complaint.statusHistory || []
        }
      })

      // 处理统计数据
      const stats = statsResponse.data || {}
      const formattedStats = {
        total: stats.total || 0,
        pending: stats.pending || 0,
        today: stats.byTime?.today || 0
    }

    this.setData({
        feedbacks: formattedFeedbacks,
        stats: formattedStats,
        loading: false
    })

    this.filterFeedbacks()

    } catch (error) {
      console.error('加载反馈数据失败:', error)
      
      this.setData({
        loading: false,
        error: error.message || '加载数据失败，请稍后重试'
      })

      wx.showToast({
        title: error.message || '加载数据失败',
        icon: 'none',
        duration: 2000
      })
    }
  },

  // 获取类型显示名称
  getTypeDisplayName(type) {
    const typeNames = {
      'service': '服务态度',
      'efficiency': '办事效率', 
      'facility': '设施环境',
      'other': '其他建议'
    }
    return typeNames[type] || '其他建议'
  },

  // 筛选反馈
  filterFeedbacks() {
    // 确保feedbacks存在且为数组
    if (!this.data.feedbacks || !Array.isArray(this.data.feedbacks)) {
      console.warn('feedbacks数据不存在或不是数组，初始化为空数组')
      this.setData({
        feedbacks: [],
        filteredFeedbacks: []
      })
      return
    }

    let filtered = [...this.data.feedbacks]

    // 按状态筛选
    if (this.data.currentFilter !== 'all') {
      filtered = filtered.filter(item => item.status === this.data.currentFilter)
    }

    // 按关键词搜索
    if (this.data.searchKeyword) {
      const keyword = this.data.searchKeyword.toLowerCase()
      filtered = filtered.filter(item => 
        item.title.toLowerCase().includes(keyword) ||
        item.content.toLowerCase().includes(keyword) ||
        item.userName.toLowerCase().includes(keyword)
      )
    }

    this.setData({
      filteredFeedbacks: filtered
    })
  },

  // 筛选标签切换
  onFilterChange(e) {
    const { filter } = e.currentTarget.dataset
    this.setData({
      currentFilter: filter
    })
    // 重新加载数据以获取最新的筛选结果
    this.loadFeedbacks()
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
    this.filterFeedbacks()
  },

  // 查看反馈详情
  async onViewFeedback(e) {
    if (!e || !e.currentTarget || !e.currentTarget.dataset) {
      console.error('onViewFeedback: 事件对象无效', e)
      return
    }

    const { id } = e.currentTarget.dataset
    if (!id) {
      console.error('onViewFeedback: 未找到id', e.currentTarget.dataset)
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      })
      return
    }

    console.log('查看反馈详情，id:', id)
    const feedback = this.data.feedbacks.find(item => item.id == id)
    if (!feedback) {
      console.error('未找到反馈信息，id:', id, 'feedbacks:', this.data.feedbacks)
      wx.showToast({
        title: '未找到反馈信息',
        icon: 'none'
      })
      return
    }

    try {
      // 获取完整的反馈详情，包括回复历史和状态历史
      const detailResponse = await complaintsAPI.getComplaintDetail(id)
      console.log('详情API响应:', detailResponse)
      
      if (detailResponse.success) {
        const detailData = detailResponse.data
        console.log('获取到的详情数据:', detailData)
        
        // 处理回复历史记录
        const replyHistory = (detailData.replies || []).map(reply => ({
          id: reply.id,
          content: reply.content,
          replyBy: reply.replyBy,
          replyTime: this.formatDateTime(new Date(reply.replyTime)),
          status: reply.status,
          statusText: reply.status === 'processing' ? '处理中' : '已完成'
        }))
        
        // 处理状态历史记录
        const statusHistory = (detailData.statusHistory || []).map(status => ({
          from: status.from,
          to: status.to,
          action: this.getStatusActionText(status.from, status.to),
          time: this.formatDateTime(new Date(status.time))
        }))
        
        // 构建详情反馈数据
        const detailFeedback = {
          ...feedback,
          replyHistory: replyHistory,
          statusHistory: statusHistory,
          lastUpdateTime: detailData.lastUpdateTime ? this.formatDateTime(new Date(detailData.lastUpdateTime)) : null
        }
        
        console.log('处理后的详情数据:', detailFeedback)
        
        // 显示详情弹窗
        this.setData({
          detailFeedback: detailFeedback,
          showDetailModal: true
        })
        console.log('详情弹窗已打开，showDetailModal:', true)
      } else {
        throw new Error(detailResponse.message || '获取详情失败')
      }
    } catch (error) {
      console.error('获取反馈详情失败:', error)
      
      // 如果获取详情失败，使用现有数据
      const detailFeedback = {
        ...feedback,
        replyHistory: feedback.replyHistory || [],
        statusHistory: feedback.statusHistory || []
      }
      
      this.setData({
        detailFeedback: detailFeedback,
        showDetailModal: true
      })
      console.log('使用缓存数据打开详情弹窗，showDetailModal:', true)
      
      wx.showToast({
        title: '获取详情失败，使用缓存数据',
        icon: 'none',
        duration: 2000
      })
    }
  },

  // 获取状态变更动作文本
  getStatusActionText(from, to) {
    const statusNames = {
      'pending': '待处理',
      'processing': '处理中',
      'completed': '已处理',
      'cancelled': '已撤销'
    }
    return `${statusNames[from] || '未知'} → ${statusNames[to] || '未知'}`
  },

  // 关闭详情弹窗
  onCloseDetailModal() {
    this.setData({
      showDetailModal: false,
      detailFeedback: {}
    })
  },

  // 从详情弹窗跳转到回复
  onReplyFromDetail() {
    const feedback = this.data.detailFeedback
    if (feedback && feedback.id) {
      // 关闭详情弹窗
      this.setData({
        showDetailModal: false
      })
      
      // 打开回复弹窗
      setTimeout(() => {
        this.onReplyFeedback({ currentTarget: { dataset: { id: feedback.id } } })
      }, 300)
    }
  },

  // 回复反馈
  async onReplyFeedback(e) {
    const { id } = e.currentTarget.dataset
    const feedback = this.data.feedbacks.find(item => item.id == id)
    if (feedback) {
      console.log('打开回复弹窗，反馈数据:', feedback)
      console.log('回复历史记录:', feedback.replyHistory)
      
      // 获取完整的反馈详情，包括回复历史
      try {
        const detailResponse = await complaintsAPI.getComplaintDetail(id)
        if (detailResponse.success) {
          const detailData = detailResponse.data
          console.log('获取到的详情数据:', detailData)
          
          // 处理回复历史记录
          const replyHistory = (detailData.replies || []).map(reply => ({
            id: reply.id,
            content: reply.content,
            replyBy: reply.replyBy,
            replyTime: this.formatDateTime(new Date(reply.replyTime)),
            status: reply.status,
            statusText: reply.status === 'processing' ? '处理中' : '已完成'
          }))
          
          // 更新反馈数据
          const updatedFeedback = {
            ...feedback,
            replyHistory: replyHistory
          }
          
          console.log('处理后的回复历史:', replyHistory)
          
          // 根据当前状态设置默认回复状态
          let defaultReplyStatus = 'processing'
          if (feedback.status === 'completed') {
            defaultReplyStatus = 'processing' // 已完成状态重新打开时设为处理中
          } else if (feedback.status === 'processing') {
            defaultReplyStatus = 'completed' // 处理中状态继续处理时设为已完成
          }

          this.setData({
            currentFeedback: updatedFeedback,
            showReplyModal: true,
            replyContent: '',
            replyStatus: defaultReplyStatus,
            showReplyError: false
          })
        } else {
          throw new Error(detailResponse.message || '获取详情失败')
        }
      } catch (error) {
        console.error('获取反馈详情失败:', error)
        
        // 如果获取详情失败，使用现有数据
        let defaultReplyStatus = 'processing'
        if (feedback.status === 'completed') {
          defaultReplyStatus = 'processing'
        } else if (feedback.status === 'processing') {
          defaultReplyStatus = 'completed'
        }

        this.setData({
          currentFeedback: feedback,
          showReplyModal: true,
          replyContent: '',
          replyStatus: defaultReplyStatus,
          showReplyError: false
        })
        
        wx.showToast({
          title: '获取详情失败，使用缓存数据',
          icon: 'none',
          duration: 2000
        })
      }
    }
  },

  // 改变状态
  async onChangeStatus(e) {
    const { id } = e.currentTarget.dataset
    const feedback = this.data.feedbacks.find(item => item.id == id)
    if (!feedback) return

    let newStatus = ''
    let newStatusText = ''
    let newStatusClass = ''
    let actionMessage = ''
    let currentTime = this.formatDateTime(new Date())

    switch (feedback.status) {
      case 'pending':
        // 待处理状态，打开回复弹窗进行开始处理
        this.openReplyModalForStart(id, feedback)
        break
        
      case 'processing':
        // 处理中状态，打开回复弹窗进行标记完成
        this.openReplyModalForComplete(id, feedback)
        break
        
      case 'completed':
        // 对于已完成状态，调用重新处理 API
        try {
          const response = await complaintsAPI.reprocessComplaint(id)
          if (response.success) {
            newStatus = 'pending'
            newStatusText = '待处理'
            newStatusClass = 'pending'
            actionMessage = '已重新处理'
            
            // 更新反馈状态
            const updatedFeedbacks = this.data.feedbacks.map(item => {
              if (item.id == id) {
                return {
                  ...item,
                  status: newStatus,
                  statusText: newStatusText,
                  statusClass: newStatusClass,
                  lastUpdateTime: currentTime,
                  statusHistory: [
                    ...(Array.isArray(item.statusHistory) ? item.statusHistory : []),
                    {
                      from: feedback.status,
                      to: newStatus,
                      time: currentTime,
                      action: actionMessage
                    }
                  ]
                }
              }
              return item
            })

            this.setData({
              feedbacks: updatedFeedbacks
            })

            this.filterFeedbacks()
            
            // 显示成功提示
            wx.showToast({
              title: actionMessage,
              icon: 'success',
              duration: 2000
            })

            // 记录操作日志
            console.log(`反馈 ${id} 重新处理成功: ${feedback.status} → ${newStatus} (${currentTime})`)
            
            // 异步重新加载数据以获取服务器端的最新状态
            setTimeout(() => {
              this.loadFeedbacks()
            }, 1000)
          } else {
            throw new Error(response.message || '重新处理失败')
          }
        } catch (error) {
          console.error('重新处理失败:', error)
          
          wx.showToast({
            title: error.message || '重新处理失败',
            icon: 'none',
            duration: 2000
          })
        }
        break
    }
  },

  // 为开始处理打开回复弹窗
  async openReplyModalForStart(id, feedback) {
    try {
      const detailResponse = await complaintsAPI.getComplaintDetail(id)
      if (detailResponse.success) {
        const detailData = detailResponse.data
        console.log('获取到的详情数据:', detailData)
        
        // 处理回复历史记录
        const replyHistory = (detailData.replies || []).map(reply => ({
          id: reply.id,
          content: reply.content,
          replyBy: reply.replyBy,
          replyTime: this.formatDateTime(new Date(reply.replyTime)),
          status: reply.status,
          statusText: reply.status === 'processing' ? '处理中' : '已完成'
        }))
        
        // 更新反馈数据
        const updatedFeedback = {
          ...feedback,
          replyHistory: replyHistory
        }
        
        console.log('处理后的回复历史:', replyHistory)
        
        // 为开始处理设置默认回复状态为处理中
        this.setData({
          currentFeedback: updatedFeedback,
          showReplyModal: true,
          replyContent: '',
          replyStatus: 'processing', // 开始处理时默认选择处理中状态
          showReplyError: false
        })
      } else {
        throw new Error(detailResponse.message || '获取详情失败')
      }
    } catch (error) {
      console.error('获取反馈详情失败:', error)
      
      // 如果获取详情失败，使用现有数据
      this.setData({
        currentFeedback: feedback,
        showReplyModal: true,
        replyContent: '',
        replyStatus: 'processing', // 开始处理时默认选择处理中状态
        showReplyError: false
      })
      
      wx.showToast({
        title: '获取详情失败，使用缓存数据',
        icon: 'none',
        duration: 2000
      })
    }
  },

  // 为标记完成打开回复弹窗
  async openReplyModalForComplete(id, feedback) {
    try {
      const detailResponse = await complaintsAPI.getComplaintDetail(id)
      if (detailResponse.success) {
        const detailData = detailResponse.data
        console.log('获取到的详情数据:', detailData)
        
        // 处理回复历史记录
        const replyHistory = (detailData.replies || []).map(reply => ({
          id: reply.id,
          content: reply.content,
          replyBy: reply.replyBy,
          replyTime: this.formatDateTime(new Date(reply.replyTime)),
          status: reply.status,
          statusText: reply.status === 'processing' ? '处理中' : '已完成'
        }))
        
        // 更新反馈数据
        const updatedFeedback = {
          ...feedback,
          replyHistory: replyHistory
        }
        
        console.log('处理后的回复历史:', replyHistory)
        
        // 为标记完成设置默认回复状态为已完成
        this.setData({
          currentFeedback: updatedFeedback,
          showReplyModal: true,
          replyContent: '',
          replyStatus: 'completed', // 标记完成时默认选择已完成状态
          showReplyError: false
        })
      } else {
        throw new Error(detailResponse.message || '获取详情失败')
      }
    } catch (error) {
      console.error('获取反馈详情失败:', error)
      
      // 如果获取详情失败，使用现有数据
      this.setData({
        currentFeedback: feedback,
        showReplyModal: true,
        replyContent: '',
        replyStatus: 'completed', // 标记完成时默认选择已完成状态
        showReplyError: false
      })
      
      wx.showToast({
        title: '获取详情失败，使用缓存数据',
        icon: 'none',
        duration: 2000
      })
    }
  },

  // 回复内容输入
  onReplyInput(e) {
    this.setData({
      replyContent: e.detail.value,
      showReplyError: false
    })
  },

  // 选择回复状态
  onSelectStatus(e) {
    const { status } = e.currentTarget.dataset
    this.setData({
      replyStatus: status
    })
  },

  // 提交回复
  async onSubmitReply() {
    if (!this.data.replyContent.trim()) {
      this.setData({
        showReplyError: true,
        replyErrorMsg: '请输入回复内容'
      })
      return
    }

    try {
      // 调用真实的 API 接口
      const response = await complaintsAPI.replyComplaint(this.data.currentFeedback.id, {
        replyContent: this.data.replyContent,
        replyStatus: this.data.replyStatus
      })

      if (response.success) {
        // 处理服务器返回的回复数据
        const serverReply = response.reply
        const complaintUpdate = response.complaintUpdate
        
        // 构建新的回复记录
        const newReply = {
          id: serverReply.id,
          content: serverReply.content,
          replyBy: serverReply.replyBy,
          replyTime: this.formatDateTime(new Date(serverReply.replyTime)),
          status: serverReply.status,
          statusText: serverReply.status === 'processing' ? '处理中' : '已完成'
        }

        // 更新当前反馈的回复历史
        const updatedCurrentFeedback = {
          ...this.data.currentFeedback,
          replyHistory: [
            ...(this.data.currentFeedback.replyHistory || []),
            newReply
          ],
          status: complaintUpdate.status,
          statusText: complaintUpdate.status === 'processing' ? '处理中' : '已处理',
          statusClass: complaintUpdate.status === 'processing' ? 'processing' : 'completed'
        }

        // 更新反馈列表中的对应项
        const updatedFeedbacks = this.data.feedbacks.map(item => {
          if (item.id === this.data.currentFeedback.id) {
            return {
              ...item,
              replyHistory: updatedCurrentFeedback.replyHistory,
              status: updatedCurrentFeedback.status,
              statusText: updatedCurrentFeedback.statusText,
              statusClass: updatedCurrentFeedback.statusClass
            }
          }
          return item
        })

        this.setData({
          currentFeedback: updatedCurrentFeedback,
          feedbacks: updatedFeedbacks
        })

        // 重新筛选数据
        this.filterFeedbacks()
        
        // 关闭弹窗
        this.setData({
          showReplyModal: false,
          replyContent: '',
          showReplyError: false
        })

        // 显示成功消息
        const successMessage = complaintUpdate.status === 'processing' ? '回复已保存，状态已更新为处理中' : '回复已保存，状态已更新为已处理'
        
        wx.showToast({
          title: successMessage,
          icon: 'success',
          duration: 2000
        })

        console.log('回复提交成功:', response)
        
        // 异步重新加载数据以获取服务器端的最新状态
        setTimeout(() => {
          this.loadFeedbacks()
        }, 1000)
      } else {
        throw new Error(response.message || '回复提交失败')
      }

    } catch (error) {
            this.hideGlobalLoading();
      console.error('回复提交失败:', error)
      
      this.setData({
        showReplyError: true,
        replyErrorMsg: error.message || '回复提交失败，请稍后重试'
      })

      wx.showToast({
        title: error.message || '回复提交失败',
        icon: 'none',
        duration: 2000
      })
    }
  },

  // 关闭回复弹窗
  onCloseReplyModal() {
    this.setData({
      showReplyModal: false,
      replyContent: '',
      showReplyError: false
    })
  },

  // 格式化时间
  formatDateTime(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}`
  },

  // 阻止事件冒泡（虽然catchtap已经会自动阻止，但保留这个方法以防需要）
  stopPropagation(e) {
    // catchtap 已经自动阻止冒泡，这里不需要额外处理
    if (e && e.stopPropagation) {
      e.stopPropagation()
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadFeedbacks()
    
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  }
})
